package com.wsc.springbootmultidevdemo.msg.topic;

import com.rabbitmq.client.*;
import com.wsc.springbootmultidevdemo.msg.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者1
 * * 代表一个单词, # 代表没有或者很多单词
 */
public class Worker1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        String EXCHANGE_NAME = "exchange.topic.x";
        String QUEUE_NAME =  "queue.topic.q1";
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

        String[] routingKeys = {"*.orange.*"};
        for (int i = 0; i <routingKeys.length ; i++) {
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,routingKeys[i]);
        }
        System.out.println("Consumer is waiting for message");

        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body,"UTF-8");
                System.out.println("[X] received a message :" +message);
            }
        };

        channel.basicConsume(QUEUE_NAME,true,consumer);

    }
}
